<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="蜂农名字" prop="farmerId">
        <el-select v-model="queryParams.farmerId" placeholder="请选择蜂农名称" clearable @change="handleQuery">
          <el-option v-for="farmer in farmerList" :key="farmer.id" :label="farmer.farmerName" :value="farmer.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="蜂区名字" prop="areaId">
        <el-select v-model="queryParams.areaId" placeholder="请选择养蜂区名称" clearable @change="handleQuery">
          <el-option v-for="area in beeareaList" :key="area.id" :label="area.areaName" :value="area.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="定位时间" prop="locationTime">
        <el-date-picker clearable v-model="queryParams.locationTime" type="date" value-format="YYYY-MM-DD"
                        placeholder="请选择定位时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否在规划点内" prop="isInPlan" label-width="110px">
        <el-select v-model="queryParams.isInPlan" placeholder="请选择是否在规划点内" clearable>
          <el-option v-for="dict in farmer_location" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="定位备注" prop="locationRemark">
        <el-input v-model="queryParams.locationRemark" placeholder="请输入定位备注" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
                   v-hasPermi="['farmer:farmerlocation:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['farmer:farmerlocation:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['farmer:farmerlocation:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
                   v-hasPermi="['farmer:farmerlocation:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="farmerlocationList" @selection-change="handleSelectionChange" :key="tableKey">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="120px" />
      <el-table-column label="蜂农名称" align="center" prop="farmerId" >
        <template #default="scope">
          <div v-for="farmer in farmerList" :key="farmer.id">
            <template v-if="farmer.id === scope.row.farmerId">
              {{ farmer.farmerName }}
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="管理养蜂区域" align="center" prop="areaId" >
        <template #default="scope">
          <div v-for="area in beeareaList" :key="area.id">
            <template v-if="area.id === scope.row.areaId">
              {{ area.areaName }}
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="定位时间" align="center" prop="locationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.locationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否在规划点内" align="center" prop="isInPlan">
        <template #default="scope">
          <dict-tag :options="farmer_location" :value="scope.row.isInPlan" />
        </template>
      </el-table-column>
      <el-table-column label="定位备注" align="center" prop="locationRemark" />
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"  @click="handleUpdate(scope.row)"
                     v-hasPermi="['farmer:farmerlocation:edit']">修改</el-button>
          <el-button link type="primary"  @click="handleDelete(scope.row)"
                     v-hasPermi="['farmer:farmerlocation:remove']">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="getList" />

    <!-- 添加或修改蜂农定位信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="farmerlocationRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="蜂农名称" prop="farmerId">
          <el-select v-model="form.farmerId" placeholder="请选择蜂农">
            <el-option v-for="farmer in farmerList" :key="farmer.id" :label="farmer.farmerName" :value="farmer.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在养蜂区域" prop="areaId">
          <el-select v-model="form.areaId" placeholder="请选择养蜂区域">
            <el-option v-for="area in beeareaList" :key="area.id" :label="area.areaName" :value="area.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="定位时间" prop="locationTime">
          <el-date-picker clearable v-model="form.locationTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择定位时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否在规划点内" prop="isInPlan">
          <el-select v-model="form.isInPlan" placeholder="请选择是否在规划点内">
            <el-option v-for="dict in farmer_location" :key="dict.value" :label="dict.label"
                       :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="定位备注" prop="locationRemark">
          <el-input v-model="form.locationRemark" placeholder="请输入定位备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Farmerlocation">
import { listFarmerlocation, getFarmerlocation, delFarmerlocation, addFarmerlocation, updateFarmerlocation } from "@/api/farmer/farmerlocation"
import { listFarmer } from "@/api/farmer/farmer"
import { listBeearea } from "@/api/farmer/beearea" // 新增导入
const { proxy } = getCurrentInstance()
const { farmer_location } = proxy.useDict('farmer_location')

const farmerlocationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const tableKey = ref(0)  // 新增：用于触发表格重新渲染的key

const farmerList = ref([])
const beeareaList = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    farmerId: null,
    areaId: null,
    locationTime: null,
    isInPlan: null,
    locationRemark: null,
  },
  rules: {
    farmerId: [
      { required: true, message: "蜂农不能为空", trigger: "change" }
    ],
    areaId: [
      { required: true, message: "养蜂区域不能为空", trigger: "change" }
    ],
    locationTime: [
      { required: true, message: "定位时间不能为空", trigger: "blur" }
    ],
    isInPlan: [
      { required: true, message: "是否在规划点内不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询蜂农定位信息列表 */
function getList() {
  loading.value = true
  listFarmerlocation(queryParams.value).then(response => {
    farmerlocationList.value = response.rows
    total.value = response.total
    loading.value = false
  })

    listFarmer({pageNum: 1, pageSize: 1000}).then( response => {
      farmerList.value = response.rows
      tableKey.value++
    })

    listBeearea({pageNum: 1, pageSize: 1000}).then( response => {
      beeareaList.value = response.rows
      tableKey.value++
    })


}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    farmerId: null,
    areaId: null,
    longitude: null,
    latitude: null,
    locationTime: null,
    isInPlan: null,
    locationRemark: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("farmerlocationRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加蜂农定位信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getFarmerlocation(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改蜂农定位信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["farmerlocationRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFarmerlocation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addFarmerlocation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除蜂农定位信息编号为"' + _ids + '"的数据项？').then(function () {
    return delFarmerlocation(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('farmer/farmerlocation/export', {
    ...queryParams.value
  }, `farmerlocation_${new Date().getTime()}.xlsx`)
}

getList()
</script>